import React, { useState, useEffect, useRef, useCallback } from "react";
import { Spin, notification } from "antd";
import { getQueryString } from '@commonMethod'
import { NoAccess } from '@components'

import mapUtils from "./utils";
import Search from "./components/Search";
import AreaDetails from "./components/AreaDetails";

import { session } from '@core'

import { decryptSceneTypeToPage, getUnits, getRisks } from "@apis/markAreaApi";

import styles from "./styles/map.module.css";

const Map = () => {
  const [spinning, setSpinning] = useState(false);
  const [isNoAccess, setIsNoAccess] = useState(false);
  const [addressList, setAddressList] = useState([]); // 地址列表
  const drawerRef = useRef('drawerRef')
  const { initMap, setLastAreaName, searchSubmit } = mapUtils(setSpinning, setAddressList, drawerRef)

  const encryptData = getQueryString('encryptData')
  const partnerCode = getQueryString('partnerCode')

  const initData = async () => {
    setSpinning(true)
    const { data, error } = await decryptSceneTypeToPage();
    console.log('data值：', data);
    setSpinning(false)
    if (error) {
      setIsNoAccess(true)
      session.clear()
      return
    }
    session.set('token', data.token)

    getUnits()
    getRisks()

    initMap();
    setLastAreaName();

  }

  useEffect(() => {

    try { // 检测 BMapGL 是否存在
      new BMapGL.Geocoder()
    } catch (error) {
      console.error(error);
      notification.error({
        message: '温馨提醒',
        description: '地图加载失败，请检查网络或尝试刷新页面',
        placement: 'top',
      })
      return
    }

    if (partnerCode && encryptData) {
      initData()
      return
    }

    getUnits()
    getRisks()

    setTimeout(() => {
      initMap();
      setLastAreaName();
    }, 0);
  }, []);

  const submit = useCallback((formData) => {
    searchSubmit(formData)
  }, [])

  const spinOption = {
    size: "large",
    tip: "正在加载中...",
    style: {
      // position: "fixed",
      height: "100%",
      maxHeight: "none",
    },
    spinning,
  };

  return (
    <div className={`page-content ${styles.map}`}>
      <Spin {...spinOption}>
        {isNoAccess ? <NoAccess /> : <>
          <Search list={addressList} submit={submit} />
          <div id="container" className={styles.container}></div>
          <AreaDetails drawerRef={drawerRef} />
        </>}
      </Spin>
    </div>
  );
};

export default Map;
